package com.tianlang.security;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.tianlang.domain.pojo.Account;
import com.tianlang.domain.pojo.Role;
import com.tianlang.service.IBaseManager;
import com.tianlang.util.StringUtil;

/**
 * 该类的主要作用是为Spring Security提供一个经过用户认证后的UserDetails。
 * 该UserDetails包括用户名、密码、是否可用、是否过期等信息。
 * 
 * @author mchp
 *
 */
@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {

	private static Logger log = Logger.getLogger(MyUserDetailsServiceImpl.class);

	@Autowired
	private IBaseManager baseManager;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		if (StringUtil.isEmpty(username)) {
			log.info("MyUserDetailsService==loadUserByUsername==用户名为空");
			throw new UsernameNotFoundException("用户名不能为空!");
		}
		Map<String, Object> searchMap = Maps.newHashMapWithExpectedSize(4);
		searchMap.put("userName", username);
		Account account = (Account) baseManager.getObjectByParams(Account.class, searchMap);
		if (account == null) {
			log.info("MyUserDetailsService==loadUserByUsername==用户名不存在");
			throw new UsernameNotFoundException("用户名不存在!");
		}
		List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
		// 得到用户的权限
		List<Role> roles = account.getRoles();
		for (Role role : roles) {
			String auth = role.getTag();
			if (StringUtil.isNotEmpty(auth)) {
				GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + auth);
				auths.add(authority);
			}
		}
		return new User(username, account.getPassword(), auths);
	}
}
